from celery import shared_task
from ..models import Cards, SystemConfig
from LogisticsCard.apis.iot_card_manage_api import single_card_detail_query, card_batch_info_query
from time import sleep

@shared_task
def card_info_task():
    # 卡信息更新任务
    # 查询所有卡并按iccid排序
    cards = Cards.objects.filter( delete_at__isnull=True).all().order_by('iccid')
    iccid_list = [card.iccid for card in cards if card.iccid]
    # 按连续区间分组，segment为“首号-尾号”格式
    iccid_segments = []
    if iccid_list:
        start = iccid_list[0]
        end = iccid_list[0]
        for iccid in iccid_list[1:]:
            # 判断是否连续（假设iccid为数字字符串）
            try:
                if int(iccid) == int(end) + 1:
                    end = iccid
                else:
                    iccid_segments.append(f"{start}-{end}")
                    start = iccid
                    end = iccid
            except Exception:
                # 若iccid不是纯数字，直接分段
                iccid_segments.append(f"{start}-{end}")
                start = iccid
                end = iccid
        iccid_segments.append(f"{start}-{end}")
    print(f"分组后的iccid区间: {iccid_segments}")
    # 调用批量查询卡信息接口更新卡信息
    api_user = SystemConfig.objects.get(key='api_user').value
    api_pass = SystemConfig.objects.get(key='api_pass').value
    #segment数据是类似 “89860412101871055784-89860412101871055794”的值 iccid（19、20）位，查询一段，首号和尾号之间用”-”连接
    for segment in iccid_segments:
        # 每次接口调用前休眠1秒
        sleep(1)
        # 判断segment是否为单卡（无'-'）还是区间
        if '-' in segment:
            # 卡段，调用批量接口
            try:
                res = card_batch_info_query(userName=api_user, passWord=api_pass, iccid_list=segment)
            except Exception as e:
                print(f"批量接口调用异常: {e}")
                continue
        else:
            # 单卡，调用单卡接口
            try:
                res = single_card_detail_query(userName=api_user, passWord=api_pass, iccid=segment)
            except Exception as e:
                print(f"单卡接口调用异常: {e}")
                continue
        if isinstance(res, str):
            print(res)
            continue
        # 判断批量或单卡返回结构
        if res and res.get('status') == 0:
            data = res.get('data', {})
            if 'totalCount' in data:
                # 批量接口，records为卡信息数组
                card_data = data.get('records', [])
                for card_info in card_data:
                    iccid = card_info.get('iccid')
                    try:
                        card = Cards.objects.get(iccid=iccid)
                        for field, value in card_info.items():
                            if hasattr(card, field):
                                setattr(card, field, value)
                        card.save()
                    except Cards.DoesNotExist:
                        print(f"卡 {iccid} 不存在于数据库中")
            else:
                # 单卡接口，data即为卡信息
                card_info = data
                iccid = card_info.get('iccid')
                try:
                    card = Cards.objects.get(iccid=iccid)
                    for field, value in card_info.items():
                        if hasattr(card, field):
                            setattr(card, field, value)
                    card.save()
                except Cards.DoesNotExist:
                    print(f"卡 {iccid} 不存在于数据库中")
        else:
            print(f"接口返回错误或无数据: {res.get('message', '未知错误')}")
    print("卡信息更新任务完成")
